package cn.layku.web.config;

import cn.layku.web.util.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ApiResult<Object> validExceptionHandler(MethodArgumentNotValidException e) {
        LOGGER.error("参数异常全局处理validExceptionHandler,message:{}", e.getMessage());
        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        for (ObjectError error : errors) {
            errorMsg.append(error.getDefaultMessage()).append(";");
        }
        return ApiResult.failResult(500, errorMsg.toString());
    }

    @ExceptionHandler({RuntimeException.class, Exception.class})
    public ApiResult<Object> exceptionHandler(Exception e) {
        LOGGER.error("其他异常全局处理exceptionHandler:", e);
        return ApiResult.failResult(500, "未知服务异常");
    }
}
